package com.maxd.service.weixin;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.maxd.model.*;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.pay.PayDetailsJpaRepository;
import com.maxd.respository.pay.PayDetailsRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.service.money.IMoneyDetailsService;
import com.maxd.service.userMoney.UserMoneyDetailsService;
import com.maxd.service.userMoney.UserMoneyService;
import com.maxd.utils.AmountCalUtils;
import com.maxd.utils.Config;
import com.maxd.utils.MD5Util;
import com.maxd.utils.WXConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author fang
 * @date 2020/2/26
 */
@Service
public class WxServiceImpl implements WxService {
    private static final String SPBILL_CREATE_IP = "127.0.0.1";
    private static final String TRADE_TYPE_APP = "APP";
    private static final String TRADE_TYPE_NATIVE = "NATIVE";
    private static final String TRADE_TYPE_JSAPI = "JSAPI";


    private final Logger log = LoggerFactory.getLogger(WxServiceImpl.class);

    @Autowired
    private PayDetailsJpaRepository payDetailsJpaRepository;
    @Autowired
    private PayDetailsRepository payDetailsRepository;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private IMoneyDetailsService moneyDetailsService;

    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String payBack(String resXml,Integer type) {
        WXConfig config = null;
        try {
            config = new WXConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(type==1){
            config.setAppId(commonRepository.findOne(74).getValue());
        }else if(type==2){
            config.setAppId(commonRepository.findOne(5).getValue());
        }else{
            config.setAppId(commonRepository.findOne(45).getValue());
        }
        config.setKey(commonRepository.findOne(75).getValue());
        config.setMchId(commonRepository.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        try {
            notifyMap = WXPayUtil.xmlToMap(resXml);         // 调用官方SDK转换成map类型数据
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {//验证签名是否有效，有效则进一步处理

                String return_code = notifyMap.get("return_code");//状态
                String out_trade_no = notifyMap.get("out_trade_no");//商户订单号
                if (return_code.equals("SUCCESS")) {
                    if (out_trade_no != null) {
                        // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户的订单状态从退款改成支付成功
                        // 注意特殊情况：微信服务端同样的通知可能会多次发送给商户系统，所以数据持久化之前需要检查是否已经处理过了，处理了直接返回成功标志
                        //业务数据持久化
                        PayDetails payDetails=payDetailsRepository.selectByOrderId(out_trade_no);
                        if(payDetails.getState()==0){
                            payDetailsRepository.updateState(payDetails.getId(),1,new Date());
                            userMoneyService.updateMoney(1,payDetails.getUserId(),payDetails.getMoney());
                            UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                            userMoneyDetails.setUserId(payDetails.getUserId());
                            userMoneyDetails.setTitle("充值："+payDetails.getMoney());
                            userMoneyDetails.setContent("微信充值金额："+payDetails.getMoney());
                            userMoneyDetails.setType(1);
                            userMoneyDetails.setMoney(payDetails.getMoney());
                            userMoneyDetails.setCreateTime(sdf.format(new Date()));
                            userMoneyDetailsService.save(userMoneyDetails);
                            MoneyDetails moneyDetails=new MoneyDetails();
                            moneyDetails.setUserId(payDetails.getUserId());
                            moneyDetails.setTitle("充值："+payDetails.getMoney());
                            moneyDetails.setContent("微信充值金额："+payDetails.getMoney());
                            moneyDetails.setType(1);
                            moneyDetails.setMoney(payDetails.getMoney());
                            moneyDetails.setCreateTime(sdf.format(new Date()));
                            moneyDetailsService.save(moneyDetails);
                        }
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                }else{
                }
                return xmlBack;
            } else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
                System.err.println("手机支付回调通知签名错误");
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        } catch (Exception e) {
            System.err.println("手机支付回调通知失败" + e);
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        return xmlBack;
    }


    @Override
    public String getGeneralOrder(){
        Date date=new Date();
        String newString = String.format("%0"+4+"d", (int)((Math.random()*9+1)*1000));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(date);
        return format+newString;
    }


    /**
     * 微信支付
     * @param money  金额 整数
     * @param userId  用户id
     * @param type 类型 1App支付 2Web支付 3jsApi
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Map doUnifiedOrder(String money,Long userId,Integer type) throws Exception {
        String url;
        CommonInfo one2 = commonRepository.findOne(19);
        if(type==3){
            url=one2.getValue()+"/tao/api/order/notifyJsApi";
        }else if(type==1){
            url=one2.getValue()+"/tao/api/order/notify";
        }else{
            url=one2.getValue()+"/tao/api/order/notifyMp";
        }
        log.info("回调地址："+url);
        String currentTimeMillis=(System.currentTimeMillis() / 1000)+"";
        String generateNonceStr = WXPayUtil.generateNonceStr();
        String outTradeNo=getGeneralOrder();
        WXConfig config = new WXConfig();
        if(type==1){
            config.setAppId(commonRepository.findOne(74).getValue());
        }else if(type==2){
            config.setAppId(commonRepository.findOne(5).getValue());
        }else{
            config.setAppId(commonRepository.findOne(45).getValue());
        }
        config.setKey(commonRepository.findOne(75).getValue());
        config.setMchId(commonRepository.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", generateNonceStr);
        String body = Config.BASE_NAME;
        data.put("body", body);
        //生成商户订单号，不可重复
        data.put("out_trade_no", outTradeNo);
        data.put("total_fee", money);
        //自己的服务器IP地址
        data.put("spbill_create_ip", SPBILL_CREATE_IP);
        //异步通知地址（请注意必须是外网）
        data.put("notify_url", url);
        //交易类型
        data.put("trade_type", type==1?TRADE_TYPE_APP:type==2?TRADE_TYPE_NATIVE:TRADE_TYPE_JSAPI);
        //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        data.put("attach", "");
        data.put("sign", WXPayUtil.generateSignature(data, config.getKey(),
                WXPayConstants.SignType.MD5));
        UserInfo userInfo = userJpaRepository.findById(userId).orElse(null);
        if(type==3){
            data.put("openid", userInfo.getOpenId());
        }else if(type==2){
            data.put("openid", userInfo.getMpId());
        }
        //使用官方API请求预付订单
        Map<String, String> response = wxpay.unifiedOrder(data);
        if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数
            //创建订单信息
            PayDetails payDetails=new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(outTradeNo);
            payDetails.setUserId(userId);
            payDetails.setMoney(AmountCalUtils.divide(Double.parseDouble(money),100));
            payDetails.setClassify(1);
            payDetailsJpaRepository.save(payDetails);
            if(type==1){
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("package", "Sign=WXPay");
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                        WXPayConstants.SignType.MD5));
                param.put("outtradeno", outTradeNo);
                return param;
            }else{
                Map<String, String> param = new HashMap<>();
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("noncestr", generateNonceStr);
                param.put("timestamp",currentTimeMillis);
                    /*param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                            WXPayConstants.SignType.MD5));*/
                String stringSignTemp = "appId=" + config.getAppID() + "&nonceStr=" + generateNonceStr + "&package=prepay_id=" + response.get("prepay_id") + "&signType=MD5&timeStamp=" + currentTimeMillis+ ""+"&key="+config.getKey();
                String sign = MD5Util.md5Encrypt32Upper(stringSignTemp).toUpperCase();
                param.put("sign",sign);
                param.put("outtradeno", outTradeNo);
                param.put("package", "prepay_id="+response.get("prepay_id"));//给前端返回的值
                param.put("mweb_url", response.get("mweb_url"));
                param.put("trade_type", response.get("trade_type"));
                param.put("return_msg", response.get("return_msg"));
                param.put("result_code", response.get("result_code"));
                param.put("signType", "MD5");
                return param;
            }
        }
        throw new Exception("下单失败");
    }
}